package com.hupu.jrs.ui.main

import android.app.Fragment
import android.content.Context
import android.text.TextUtils
import android.view.MenuItem
import com.hupu.jrs.AppManager
import com.hupu.jrs.R
import com.hupu.jrs.components.storage.UserStorage
import com.hupu.jrs.injector.PerActivity
import com.hupu.jrs.otto.AccountChangeEvent
import com.hupu.jrs.otto.ChangeThemeEvent
import com.hupu.jrs.otto.LoginSuccessEvent
import com.hupu.jrs.otto.MessageReadEvent
import com.hupu.jrs.ui.browser.BrowserFragment
import com.hupu.jrs.ui.forum.ForumListFragment
import com.hupu.jrs.ui.thread.collect.CollectThreadListFragment
import com.hupu.jrs.ui.thread.recommend.RecommendThreadListFragment
import com.hupu.jrs.util.SettingPrefUtil
import com.hupu.jrs.util.ToastUtil
import com.hupu.jrs.util.UpdateAgent
import com.squareup.otto.Bus
import com.squareup.otto.Subscribe
import javax.inject.Inject
import rx.Observable
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers

/**
 * Created by sll on 2016/3/17.
 */
@PerActivity
class MainPresenter @Inject
constructor(private val mUserStorage: UserStorage, private val mUserDao: UserDao, private val mBus: Bus,
            private val mNotificationObservable: Observable<Int>, private val mUpdateAgent: UpdateAgent, private val mContext: Context) : MainContract.Presenter {

    private var mSubscription: Subscription? = null
    private var mMainView: MainContract.View? = null
    private var count = 0

    private var mExitTime: Long = 0

    private val isCanExit: Boolean
        get() {
            if (System.currentTimeMillis() - mExitTime > 2000) {
                ToastUtil.showToast("再按一次退出程序")
                mExitTime = System.currentTimeMillis()
                return false
            }
            return true
        }

    override val isLogin: Boolean
        get() = mUserStorage.isLogin()

    fun attachView(view: MainContract.View) {
        mMainView = view
        mBus.register(this)
        initUserInfo()
        initNotification()
        mUpdateAgent.checkUpdate()
    }

    private fun initUserInfo() {
        mMainView!!.renderUserInfo(if (isLogin) mUserStorage.getUser() else null)
    }

    private fun initNotification() {
        if (isLogin && !TextUtils.isEmpty(SettingPrefUtil.getHuPuSign(mContext))) {
            mSubscription = mNotificationObservable.subscribe({ integer ->
                if (integer == null) {
                    ToastUtil.showToast("登录信息失效，请重新登录")
                    mUserDao.queryBuilder()
                            .where(UserDao.Properties.Uid.eq(mUserStorage.getUid()))
                            .buildDelete()
                            .executeDeleteWithoutDetachingEntities()
                    mUserStorage.logout()
                    mMainView!!.showLoginUi()
                } else {
                    count = integer
                    mMainView!!.renderNotification(integer)
                }
            }) { }
        }
    }

    private fun toLogin() {
        mMainView!!.showLoginUi()
        ToastUtil.showToast("请先登录")
    }

    override fun onNightModelClick() {
        SettingPrefUtil.setNightModel(mContext, !SettingPrefUtil.getNightModel(mContext))
        mMainView!!.reload()
    }

    override fun onNotificationClick() {
        if (isLogin) {
            mMainView!!.showMessageUi()
        } else {
            toLogin()
        }
    }

    override fun onCoverClick() {
        if (isLogin) {
            mMainView!!.showUserProfileUi(mUserStorage.getUid())
        } else {
            toLogin()
        }
        mMainView!!.closeDrawers()
    }

    override fun onNavigationClick(item: MenuItem) {
        when (item.itemId) {
            R.id.nav_recommend, R.id.nav_collect, R.id.nav_topic, R.id.nav_nba, R.id.nav_my, R.id.nav_cba, R.id.nav_gambia, R.id.nav_equipment, R.id.nav_fitness, R.id.nav_football, R.id.nav_intel_football, R.id.nav_sport -> {
                var mFragment: Fragment? = null
                val id = item.itemId
                if (id == R.id.nav_collect) {
                    if (isLogin) {
                        mFragment = CollectThreadListFragment()
                    } else {
                        toLogin()
                    }
                } else if (id == R.id.nav_topic) {
                    if (isLogin) {
                        mFragment = BrowserFragment.newInstance(mUserStorage.getUser().getThreadUrl(), "我的帖子")
                    } else {
                        toLogin()
                    }
                } else if (id == R.id.nav_recommend) {
                    mFragment = RecommendThreadListFragment()
                } else {
                    if (isLogin || id != R.id.nav_my) {
                        mFragment = ForumListFragment.newInstance(Constants.mNavMap.get(id))
                    } else {
                        toLogin()
                    }
                }
                if (mFragment != null) {
                    item.isChecked = true
                    mMainView!!.setTitle(item.title)
                    mMainView!!.showFragment(mFragment)
                }
            }
            R.id.nav_setting -> mMainView!!.showSettingUi()
            R.id.nav_feedback -> mMainView!!.showFeedBackUi()
            R.id.nav_about -> mMainView!!.showAboutUi()
        }
        mMainView!!.closeDrawers()
    }

    override fun showAccountMenu() {
        Observable.create<List<User>> { subscriber ->
            val userList = mUserDao.queryBuilder().list()
            for (bean in userList) {
                if (bean.getUid().equals(mUserStorage.getUid())) {
                    userList.remove(bean)
                    break
                }
            }
            subscriber.onNext(userList)
        }
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe { users ->
                    val items = arrayOfNulls<String>(users.size + 1)
                    for (i in users.indices)
                        items[i] = users[i].getUserName()
                    items[items.size - 1] = "账号管理"
                    mMainView!!.renderAccountList(users, items)
                }
    }

    override fun onAccountItemClick(position: Int, users: List<User>, items: Array<String>) {
        if (position == items.size - 1) {
            // 账号管理
            mMainView!!.showAccountUi()
        } else {
            mUserStorage.login(users[position])
            initUserInfo()
        }
        mMainView!!.closeDrawers()
    }

    override fun exist() {
        if (isCanExit) {
            AppManager.getAppManager().AppExit(mContext)
        }
    }

    fun detachView() {
        mBus.unregister(this)
        count = 0
        if (mSubscription != null && !mSubscription!!.isUnsubscribed) {
            mSubscription!!.unsubscribe()
        }
        mMainView = null
    }

    @Subscribe
    fun onChangeThemeEvent(event: ChangeThemeEvent) {
        mMainView!!.reload()
    }

    @Subscribe
    fun onLoginSuccessEvent(event: LoginSuccessEvent) {
        initUserInfo()
    }

    @Subscribe
    fun onAccountChangeEvent(event: AccountChangeEvent) {
        initUserInfo()
    }

    @Subscribe
    fun onMessageReadEvent(event: MessageReadEvent) {
        if (count >= 1) {
            count--
        }
        mMainView!!.renderNotification(count)
    }
}
